//
//  UIImage+Extension.swift
//  YangFoundation
//
//  Created by yuyang on 2021/12/21.
//

import Foundation
import Photos

public extension UIImage {
    static func compressImageQuality(_ image: UIImage, toByte maxLength: Int) -> UIImage {
        var resultImage: UIImage = image
        
        let tempData: NSData = image.jpegData(compressionQuality: 1)! as NSData
        print("压缩前的大小-\(tempData.count / 1024)")
        
        var data: NSData = image.jpegData(compressionQuality: 0.5)! as NSData
        print("压缩前的大小-\(data.count / 1024)")
        var lastDataLength = 0
        while data.length > maxLength && data.length != lastDataLength {
            lastDataLength = data.length
            let ratio: CGFloat = CGFloat(maxLength) / CGFloat(data.length)
            print("Ratio =", ratio)
            let size = CGSize(width: resultImage.size.width * sqrt(CGFloat(ratio)), height: resultImage.size.height * sqrt(CGFloat(ratio)))
            if size.width < 640 && size.height < 480 {
                break
            }

            UIGraphicsBeginImageContext(size)
            resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            resultImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            data = resultImage.jpegData(compressionQuality: 1)! as NSData
        }
        print("压缩后的大小-\(data.count / 1024)")
        return resultImage
    }

    func compressLessThan(_ bytesLimit: Int) -> Data? {
        guard var result: Data = self.jpegData(compressionQuality: 1) else { return nil }

        var compressionQuality = 1.0
        while result.count > bytesLimit, compressionQuality > 0.1 {
            compressionQuality -= 0.1
            if let compressed = self.jpegData(compressionQuality: CGFloat(compressionQuality)) {
                result = compressed
            } else {
                break
            }
        }
        return result
    }

    // 图片压缩
    func resize(_ bytesLimit: Int, _ maxHeight: CGFloat = 108.0, _ maxWidth: CGFloat = 108.0) -> Data? {
        var actualHeight = self.size.height
        var actualWidth = self.size.width

        let maxHeight: CGFloat = maxHeight
        let maxWidth: CGFloat = maxWidth
        var imgRatio = actualWidth / actualHeight
        let maxRatio = maxWidth / maxHeight

        if actualHeight > maxHeight || actualWidth > maxWidth {
            if imgRatio < maxRatio {
                // adjust width according to maxHeight
                imgRatio = maxHeight / actualHeight
                actualWidth = imgRatio * actualWidth
                actualHeight = maxHeight
            } else if imgRatio > maxRatio {
                // adjust height according to maxWidth
                imgRatio = maxWidth / actualWidth
                actualHeight = imgRatio * actualHeight
                actualWidth = maxWidth
            } else {
                actualHeight = maxHeight
                actualWidth = maxWidth
            }
        }

        let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
        UIGraphicsBeginImageContext(rect.size)
        self.draw(in: rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return img?.compressLessThan(bytesLimit)
    }

    /// 图片压缩
    static func imageCompress(image: UIImage) -> Data {
        var imgData = image.jpegData(compressionQuality: 1)
        if imgData!.count > 100 * 1024 {
            if imgData!.count > 1024 * 1024 { // 1M以及以上
                imgData = image.jpegData(compressionQuality: 0.1)
            } else if imgData!.count > 512 * 1024 { // 1M以及以上
                imgData = image.jpegData(compressionQuality: 0.3)
            } else if imgData!.count > 200 * 1024 {
                // 0.25M-0.5M
                imgData = image.jpegData(compressionQuality: 0.5)
            } else {
                imgData = image.jpegData(compressionQuality: 0.8)
            }
        }
        return imgData!
    }

    /// 创建一个纯色image, 用途未知
    static func createColorImage(_ color: UIColor, _ size: CGSize) -> UIImage {
        let rect = CGRect.init(x: 0.0, y: 0.0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }

}

public extension UIImage {
    /// 保存图片到本地
    func saveImageToLocal(completion: @escaping (Bool, Error?) -> Void) {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: self)
        }) { (isSuccess, error) in
            print("\(isSuccess)----\(String(describing: error))")
            if isSuccess {
                
            } else {
                print("error---->\(String(describing: error))")
    
            }
            completion(isSuccess, error)
        }
    }

    /// 存储图片 到沙盒
    static func saveImage(image: UIImage, fileName: String) -> String {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = path.appending("/" + fileName)
        let data: Data = image.jpegData(compressionQuality: 1)!
        FileManager.default.createFile(atPath: filePath, contents: data, attributes: nil)
        return filePath
    }
}
